package com.neusoft.utils.tpl.res;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.neusoft.utils.string.StringUtil;
import com.neusoft.utils.tpl.DirectiveUtils;
import com.neusoft.utils.tpl.bean.ResBean;
import com.neusoft.utils.tpl.help.ReadJsonToMap;
import com.neusoft.utils.web.RequestUtils;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

public class JsMinDirective implements TemplateDirectiveModel {
	public static final String PARAM_SRC = "src";
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
		String src = DirectiveUtils.getString(PARAM_SRC, params);
		HttpServletRequest req =RequestUtils.getRequest();
		String base=req.getContextPath();
		Map<String, String> configMap =ReadJsonToMap.read(getFile("commonConfig/js.json"));
		String[] jsSrcs = src.split(",");
		List<ResBean> resList = new ArrayList<ResBean>();
		for (String jsStr : jsSrcs) {
			if (null == configMap.get(jsStr)) {
				boolean isCdn=isCdn(jsStr);
				long time = getFileTime(jsStr,isCdn);
				jsStr=getFileStr(jsStr,isCdn);
				resList.add(new ResBean().setPath(jsStr).setTime(time).setIsCdn(isCdn));
			} else {
				String[] jsSubSrcs = configMap.get(jsStr).split(",");
				for (String jsSubSrc : jsSubSrcs) {
					boolean isCdn=isCdn(jsSubSrc);
					long time = getFileTime(jsSubSrc,isCdn);
					jsSubSrc=getFileStr(jsSubSrc,isCdn);
					resList.add(new ResBean().setPath(jsSubSrc).setTime(time).setIsCdn(isCdn));
				}
			}
		}
		String result ="";
		boolean orgFlag=false;
		String s = req.getQueryString();
		if (null != s && !StringUtil.isBlank(s)) {
			if(s.endsWith("@")){
				orgFlag=true;
			}
		}
		if(!orgFlag){
			  result=renderJsList(resList,base);
		}else{
			result=renderOrgJsList(resList,base);
		}  
	    env.getOut().append(result);
	}
    private String renderJsList(List<ResBean> resList,String base){
    	StringBuffer resultSb=new StringBuffer();
	    for (ResBean resBean : resList) {
	    	if(resBean.getIsCdn()){
	    		resultSb.append(StringUtil.format("<script src=\"{0}\"></script>",resBean.getPath())).append("\r\n");	
	    	}else{
	    		String path=resBean.getPath();
	    		if(!path.endsWith(".min.js")){
	    			path=path.substring(0, path.length() - ".js".length()) + ".min.js";
	    		}
	    		resultSb.append(StringUtil.format("<script src=\"{0}/{1}?v={2}\"></script>",base,path,resBean.getTime().toString())).append("\r\n");	
	    	}	    	
		}
	    return resultSb.toString();
    }
    private String renderOrgJsList(List<ResBean> resList,String base){
    	StringBuffer resultSb=new StringBuffer();
	    for (ResBean resBean : resList) {
	    	if(resBean.getIsCdn()){
	    		resultSb.append(StringUtil.format("<script src=\"{0}\"></script>",resBean.getPath())).append("\r\n");	
	    	}else{
	    		String path=resBean.getPath();
	    		resultSb.append(StringUtil.format("<script src=\"{0}/{1}?v={2}\"></script>",base,path,resBean.getTime().toString())).append("\r\n");	
	    	}	    	
		}
	    return resultSb.toString();
    }
	private long getFileTime(String path,boolean isCdn) {
		if(isCdn){
			return 1L;
		}
		return new File(RequestUtils.getWebRealPath(path)).lastModified();
	}
	private boolean isCdn(String path){
		if(path.startsWith("@")){
			return true;
		}
		return false;
	}
	private String getFileStr(String path,boolean isCdn) {
		if(isCdn){
			return path.substring(1, path.length());
		}
		return path;
	}

	private File getFile(String path) {
		return new File(RequestUtils.getWebRealPath(path));
	}

}
